package com.alibaba.dubbo.common.resolver;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class DefaultResolver implements Resolver {

	@SuppressWarnings("rawtypes")
	@Override
	public Object resolve(Map value, Class<?> target) throws Exception {
		HashMap<String, Field> fieldMap = new HashMap<String, Field>();
		Class<?> cl = target;
		for (; cl != null; cl = cl.getSuperclass()) {
			Field[] fields = cl.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];

				if (Modifier.isTransient(field.getModifiers())
						|| Modifier.isStatic(field.getModifiers()))
					continue;
				else if (fieldMap.get(field.getName()) != null)
					continue;

				// XXX: could parameterize the handler to only deal with public
				field.setAccessible(true);
				fieldMap.put(field.getName(), field);
			}
		}

		Object inst = target.newInstance();
		if (value != null) {
			for (Object key : value.keySet()) {
				if(key == null) continue;
				String name = key.toString();
				Field f = fieldMap.get(name);
				if(f == null) continue;
				f.set(inst, value.get(key));
			}
		}
		return inst;
	}
}
